#include"SList.h"

SListNode* BuyNode(SLTDataType x)
{
	SListNode* temp = (SListNode*)malloc(sizeof(SListNode));
	if (temp == NULL)
	{
		perror("malloc failed");
		exit(-1);
	}
	temp->data = x;
	temp->next = NULL;
	return temp;
}

void SListPrint(SListNode* plist)
{
	assert(plist);
	SListNode* temp = plist;
	while (temp != NULL)
	{
		printf("%d  ", temp->data);
		temp = temp->next;
	}
	printf("\n");
}

void SListPushFront(SListNode** pplist, SLTDataType x)
{
	assert(pplist);
	if (*pplist == NULL)
	{
		*pplist = BuyNode(x);
	}
	else
	{
		SListNode* newnode = BuyNode(x);
		newnode->next = *pplist;
		*pplist = newnode;
	}
}

void SListPushBack(SListNode** pplist, SLTDataType x)
{
	assert(pplist);
	if ((*pplist) == NULL)
	{
		*pplist = BuyNode(x);
	}
	else
	{
		SListNode* temp = (*pplist);
		while (temp->next)
		{
			temp = temp->next;
		}
		SListNode* newnode = BuyNode(x);
		temp->next = newnode;
	}
}

void SListPopFront(SListNode** pplist)
{
	assert(pplist);
	assert(*pplist);
	SListNode* temp = (*pplist)->next;
	free(*pplist);
	*pplist = temp;
}

void SListPopBack(SListNode** pplist)
{
	assert(pplist);
	assert(*pplist);
	SListNode* temp = *pplist;
	SListNode* prev = NULL;
	if ((*pplist)->next == NULL)
	{
		free(*pplist);
		*pplist = NULL;
	}
	else
	{
		while (temp->next)
		{
			prev = temp;
			temp = temp->next;
		}
		free(temp);
		prev->next = NULL;
		temp = NULL;
	}
}

SListNode* SListFind(SListNode* plist,SLTDataType x)
{
	assert(plist);
	SListNode* temp = plist;
	while (temp)
	{
		if (temp->data == x)
			return temp;
		temp = temp->next;
	}
	return temp;
}

void SListInsertAfter(SListNode* pos, SLTDataType x)
{
	assert(pos);
	SListNode* newnode = BuyNode(x);
	newnode->next = pos->next;
	pos->next = newnode;
}

void SListEraseAfter(SListNode* pos)
{
	assert(pos);
	assert(pos->next);
	SListNode* temp = pos->next->next;
	free(pos->next);
	pos->next = temp;
}

void SListDestory(SListNode* plist)
{
	assert(plist);
	while (plist)
	{
		SListNode* temp = plist;
		free(plist);
		plist = temp;
	}
}